package project.Components;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import project.Config.HttpSessionConfig;
import project.Pojo.Chat.ChatMessage;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/chat/room/{id}", configurator = HttpSessionConfig.class)
public class PrivateWebSocket {

    String id;

    static private ConcurrentHashMap<String, Session> sessionPool = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("id") final String id) {
        this.id = id;
        sessionPool.put(id, session);

    }


    //    String content;
//    String sender;
//    String receiver;
    @OnMessage
    public void onMessage(String message) throws IOException {
        JSONObject jsonObject = JSON.parseObject(message);
        String receiver = jsonObject.getString("receiver");
        String content = jsonObject.getString("content");
        sessionPool.get(receiver).getBasicRemote().sendText(content);
    }

    @OnClose
    public void onClose() {
        sessionPool.remove(id);
    }
}
